﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SalePartial.BLL.SAServiceRef;
using SalePartial.BLL;
using Telerik.Web.UI;
using System.Drawing;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Guid familyId;
            //if (HttpContext.Current.Session["familyId"] != null)
            if (Request["familyId"]!=null)
            {
                HttpContext.Current.Session["familyId"] = Request["familyId"];
                //HttpContext.Current.Session["Id"] = Request["id"];
                //sdsVendorList.SelectParameters["ID"].DefaultValue = Request["id"];
                familyId = new Guid(Request["familyId"].ToString());

                FamilyDetailFrm_Load(familyId);
                FamilyDownFrm_Load(familyId);


            }
            else
            {
                SABLL.ShowInfoMsg(this,@"无法查看，请在零件列表中至少选中一个零件！");
                return;
            }

        }
    }

    protected void SiteMapPath1_ItemDataBound(object sender, SiteMapNodeItemEventArgs e)
    {
        HyperLink hlk;
        if (e.Item.Controls[0] is HyperLink)
        {
            hlk = (HyperLink)e.Item.Controls[0];
            hlk.Attributes["target"] = e.Item.SiteMapNode["target"];
        }
    }

    //随便设置一个数。  
    private string nid()
    {
        return HttpContext.Current.Session["familyId"].ToString();
    }  


    protected void button_downDoc_Click(object sender, EventArgs e)
    {
        Guid familyId;
        if (HttpContext.Current.Session["familyId"] != null)
        {
            familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());

        }
        else
        {
            SABLL.ShowInfoMsg(this, @"无法下载，请在零件列表中至少选中一个零件！");
            return;
        }
        FamilyAttrInfo familyAttrInfo = SABLL.GetFamilyAttrInfoByType(familyId,
            FamilyAttrType.kReference);

        if (familyAttrInfo != null && !String.IsNullOrEmpty(familyAttrInfo.ReferenceName) &&
            familyAttrInfo.ReferenceBinary != null && familyAttrInfo.ReferenceBinary.Length > 0)
        {
            try
            {
                //远程下载文件 小文件
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(familyAttrInfo.ReferenceName).Replace("+"," ").ToString());
                HttpContext.Current.Response.BinaryWrite(familyAttrInfo.ReferenceBinary);
                Response.Flush();
                Response.Close();
            }
            catch (Exception)
            {
            }
            //SABLL.ShowInfoMsg(this, String.Format("保存文档成功！"));
        }
        else
        {
            //no referece document.
            SABLL.ShowInfoMsg(this, @"无可下载的文档资料！");
        }
    }


    protected void model_downDoc_Click(object sender, EventArgs e)
    {
        Guid familyId;
        if (HttpContext.Current.Session["familyId"] != null)
        {
            familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());

        }
        else
        {
            SABLL.ShowInfoMsg(this, @"无法下载，请在零件列表中至少选中一个零件！");
            return;
        }
        FamilyAttrInfo familyAttrInfo = SABLL.GetFamilyAttrInfoByType(familyId,
            FamilyAttrType.kModelPic);if (familyAttrInfo != null && !String.IsNullOrEmpty(familyAttrInfo.ModelPicName) &&
            familyAttrInfo.ModelPicBinary != null && familyAttrInfo.ModelPicBinary.Length > 0)
        {
            try
            {
                //远程下载文件 小文件
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(familyAttrInfo.ModelPicName).Replace("+", " ").ToString());
                HttpContext.Current.Response.BinaryWrite(familyAttrInfo.ModelPicBinary);
                Response.Flush();
                Response.Close();
            }
            catch (Exception)
            {
            }
            //SABLL.ShowInfoMsg(this, String.Format("保存文档成功！"));
        }
        else
        {
            //no referece document.
            SABLL.ShowInfoMsg(this, @"无可下载的文档资料！");
        }
    }


    protected void engineering_downDoc_Click(object sender, EventArgs e)
    {
        Guid familyId;
        if (HttpContext.Current.Session["familyId"] != null)
        {
            familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());

        }
        else
        {
            SABLL.ShowInfoMsg(this, @"无法下载，请在零件列表中至少选中一个零件！");
            return;
        }
        FamilyAttrInfo familyAttrInfo = SABLL.GetFamilyAttrInfoByType(familyId,
            FamilyAttrType.kDrawPic); if (familyAttrInfo != null && !String.IsNullOrEmpty(familyAttrInfo.DrawPicName) &&
             familyAttrInfo.DrawPicBinary != null && familyAttrInfo.DrawPicBinary.Length > 0)
        {
            try
            {
                //远程下载文件 小文件
                Response.ClearContent();
                Response.ClearHeaders();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(familyAttrInfo.DrawPicName).Replace("+", " ").ToString());
                HttpContext.Current.Response.BinaryWrite(familyAttrInfo.DrawPicBinary);
                Response.Flush();
                Response.Close();
            }
            catch (Exception)
            {
            }
            SABLL.ShowInfoMsg(this, String.Format("保存文档成功！"));
        }
        else
        {
            //no referece document.
            SABLL.ShowInfoMsg(this, @"无可下载的文档资料！");
        }
    }


    private void FamilyDetailFrm_Load(Guid familyId)
        {
            //get data.
            FamilyInfo m_familyInfo = SABLL.GetFamilyInfo(familyId);

            FamilyAttrInfo familyAttr = SABLL.GetFamilyAttrInfo(m_familyInfo.ID);
            
            if (familyAttr == null)
            {
                SABLL.ShowErrMsg(this, SABLL.GetLastErrMsg());
                return;
            }

            //string templateFilePath, modelPicPath, drawPicPath;
            //templateFilePath = System.IO.Path.Combine(GetTempFolder(familyId), familyAttr.TemplateFileName);
            //modelPicPath = System.IO.Path.Combine(GetTempFolder(familyId), familyAttr.ModelPicName);
            //drawPicPath = System.IO.Path.Combine(GetTempFolder(familyId), familyAttr.DrawPicName);

            //templateFilePath = SABLL.SaveBinaryByPath(templateFilePath, familyAttr.TemplateFileBinary);
            //modelPicPath = SABLL.SaveBinaryByPath(modelPicPath, familyAttr.ModelPicBinary);
            //drawPicPath = SABLL.SaveBinaryByPath(drawPicPath, familyAttr.DrawPicBinary);
            //this.pictureBox_modelPic.ImageUrl = modelPicPath;
            //this.pictureBox_drawPic.ImageUrl = drawPicPath;

            //this.pictureBox_modelPic.DataValue = familyAttr.ModelPicBinary;
            //this.pictureBox_drawPic.DataValue = familyAttr.DrawPicBinary;

            //this.RadBinaryImage1.DataValue = familyAttr.ModelPicBinary;
            this.RadBinaryImage2.DataValue = familyAttr.DrawPicBinary;
            this.RadBinaryImage3.DataValue = familyAttr.ModelPicBinary;
            this.Label1.ToolTip = familyAttr.ReferenceName;
            this.Label2.ToolTip = familyAttr.ModelPicName;
            this.Label3.ToolTip = familyAttr.DrawPicName;
            this.Label4.ToolTip = m_familyInfo.Name;

            if (familyAttr.ReferenceName.Length<=15)
            this.Label1.Text = familyAttr.ReferenceName;
            else
                this.Label1.Text = familyAttr.ReferenceName.Substring(0,20)+"...";

            if (familyAttr.ModelPicName.Length <= 15)
            this.Label2.Text = familyAttr.ModelPicName;
            else
                this.Label2.Text = familyAttr.ModelPicName.Substring(0,20)+"...";

            if (familyAttr.DrawPicName.Length <= 15)
            this.Label3.Text = familyAttr.DrawPicName;
            else
                this.Label3.Text = familyAttr.DrawPicName.Substring(0,20)+"...";

            if (m_familyInfo.Name.Length <= 15)
                this.Label4.Text = m_familyInfo.Name;
            else
                this.Label4.Text = m_familyInfo.Name.Substring(0, 20) + "...";

            
           
            VendorInfo vendor = SABLL.GetVendor(m_familyInfo.VendorID);
            textBox_vendor.ToolTip = vendor.Name;
            if (vendor != null)
            {
                if (vendor.Name.Length<=15)
                this.textBox_vendor.Text = vendor.Name;
                else
                    this.textBox_vendor.Text = vendor.Name.Substring(0,10)+"...";
            } 
            if (vendor != null && vendor.Description!="") this.Vendor_Des.Text = vendor.Description;
            else this.Vendor_Des.Text = "暂无";

            StandardInfo standard = SABLL.GetStandard(m_familyInfo.StandardID);
            if (familyAttr.Description == "")
                this.richTextBox_description.Text = "暂无";
            else
            this.richTextBox_description.Text = familyAttr.Description;

            
        }

    private void FamilyDownFrm_Load(Guid familyId)
    {
        //get data.
        FamilyInfo m_familyInfo = SABLL.GetFamilyInfo(familyId);
        this.Title = "零件下载--" + m_familyInfo.DisplayName;

        List<ParameterInfo> m_keyParameters = SABLL.GetFamilyKeyParameters(m_familyInfo.ID);
        if (m_keyParameters == null)
        {
            SABLL.ShowErrMsg(this, SABLL.GetLastErrMsg());
            return;
        }

        List<ParameterInfo> m_nonCustomKeyParameters = new List<ParameterInfo>();
        List<ParameterInfo> m_customKeyParameters = new List<ParameterInfo>();

        foreach (ParameterInfo item in m_keyParameters)
        {
            if (item.IsCustom)
            {
                m_customKeyParameters.Add(item);
            }
            else
            {
                m_nonCustomKeyParameters.Add(item);
            }
            
        }

        InitListViewForNonCustomKeyParameters(m_nonCustomKeyParameters);
        InitTextBoxForCustomKeyParameters(m_customKeyParameters);

        //init model, drawing pictures.
        //get data.
        FamilyAttrInfo familyAttr = SABLL.GetFamilyAttrInfo(m_familyInfo.ID);

        if (familyAttr == null)
        {
            SABLL.ShowErrMsg(this, SABLL.GetLastErrMsg());
            return;
        }


    }
    private void InitTextBoxForCustomKeyParameters(List<ParameterInfo> m_parameters)
    {
        foreach (ParameterInfo item in m_parameters)
        {
            //set parameter title.
            if (item.IsCustom)
            {
                double lowLimit, upLimit;
                bool success = SABLL.GetLimits(item.Tag, out lowLimit, out upLimit);
                if (success)
                {
                    item.DisplayName = String.Format("{0}[{1}-{2}]", item.DisplayName, lowLimit, upLimit);
                }
                else
                {

                    //newLabel.Text = item.DisplayName;
                }

                //set text default value.
                double dDefault;
                if (SABLL.GetDefault(item.Tag, out dDefault))
                {
                    item.Value = Convert.ToString(dDefault);
                }

                //add text change event.
                //double lowLimit, upLimit;
                //if (SABLL.GetLimits(item.Tag, out lowLimit, out upLimit))
                //{
                //    newTextBox.TextChanged += new EventHandler(newTextBox_TextChanged);
                //}

            }
            else
            {
                //newLabel.Text = item.DisplayName;
            }

        }
        listBox_CustomParamList1.DataSource = m_parameters;
        listBox_CustomParamList1.DataBind();
    }
    


    protected void ddl_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
    {
        List<ParameterValueInfo> emptyConstraint = new List<ParameterValueInfo>();

        foreach (RadListViewDataItem dataitem in listBox_NonCustomParamList1.Items)
        {
            RadComboBox ddl = dataitem.FindControl("ddl") as RadComboBox;
            if (ddl != null && ddl == (RadComboBox)sender)
            {
                Guid ID = new Guid(dataitem.GetDataKeyValue("ID").ToString());

                List<ParameterValueInfo> retVals = SABLL.GetParamVals(ID, emptyConstraint);

                if (retVals == null)
                {
                    SABLL.ShowErrMsg(this, SABLL.GetLastErrMsg());
                    return;
                }

                ddl.DataSource = retVals;
                ddl.DataTextField = "Value";
                ddl.DataValueField = "ID";
                ddl.DataBind();

                if (retVals.Count > 0)
                {
                    ddl.SelectedIndex = 0;
                }
                return;
            }
            else if (ddl != null && ddl.SelectedValue != string.Empty)
            {
                ParameterValueInfo info = new ParameterValueInfo();
                info.ID = new Guid(ddl.SelectedValue);
                info.Value = ddl.Text;
                emptyConstraint.Add(info);
            }
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        ViewState["ID"] = ((RadComboBox)sender).SelectedValue;
    }

    private void InitListViewForNonCustomKeyParameters(List<ParameterInfo> m_parameters)
    {
        listBox_NonCustomParamList1.DataSource = m_parameters;
        listBox_NonCustomParamList1.DataBind();
    }


    protected void Download_Click(object sender, EventArgs e)
    {
        List<ParameterValueInfo> retList = new List<ParameterValueInfo>();
        foreach (RadListViewDataItem dataitem in listBox_NonCustomParamList1.Items)
        {
            RadComboBox ddl = dataitem.FindControl("ddl") as RadComboBox;
            if (ddl.Text == "")
            {
                SABLL.ShowInfoMsg(this, "请确保驱动参数的数据完整！");
                return;
            }
            else
            {

                DataTable dt = this.GetDataTableByUserDriverParameterSelection();
                InitSubFamilyTableGridView(dt);

            }

            this.dataGridView_subFamilyTable.SelectedIndexes.Add(0);
        }
        StartDownLoad();
    }


    private void InitSubFamilyTableGridView(DataTable dt)
    {

        if (dataGridView_subFamilyTable.Columns.Count > 0)
        {
            dataGridView_subFamilyTable.Columns.Clear();
        }
        dataGridView_subFamilyTable.AutoGenerateColumns = false;
        Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);

        int cnt = dt.Columns.Count;
        for (int i = 0; i < cnt; i++)
        {
            //GridColumn curCol = this.dataGridView_subFamilyTable.Columns[i];
            string parameterGuid = dt.Columns[i].ColumnName;
            if (parameterGuid == null || !isGuid.IsMatch(parameterGuid))
            {

            }
            else
            {
                try
                {
                    //curCol.Tag = parameterGuid;

                    ParameterInfo paramInfo = SABLL.GetFamilyParameterInfo(new Guid(parameterGuid));
                    if (paramInfo != null)
                    {
                        dt.Columns[i].ColumnName = paramInfo.DisplayName;
                        //curCol.Tag = paramInfo;
                    }
                }
                catch (Exception)
                {

                }
            }

            GridBoundColumn boundColumn = new GridBoundColumn();
            //boundColumn.UniqueName = dt.Columns[i].ColumnName.Replace(" ","");
            boundColumn.DataField = dt.Columns[i].ColumnName;
            boundColumn.HeaderText = dt.Columns[i].ColumnName;
            if (i == 0 || i == 1)
            {
                boundColumn.Visible = false;
            }

            dataGridView_subFamilyTable.Columns.Add(boundColumn);
        }
       

        this.dataGridView_subFamilyTable.DataSource = dt;
        this.dataGridView_subFamilyTable.DataBind();
    }

    private DataTable GetDataTableByUserDriverParameterSelection()
    {
        Guid familyId;
        if (HttpContext.Current.Session["familyId"] != null)
        {
            familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());

        }
        else
        {
            return null;
        }

        List<ParameterValueInfo> paramConstraints = this.GetParameterConstrains();

        DataTable dt = SABLL.GetSubFamilyTable(familyId, paramConstraints);

        if (dt == null)
        {
            SABLL.ShowInfoMsg(this, SABLL.GetLastErrMsg());
        }
        return dt;
    }


    private List<ParameterValueInfo> GetParameterConstrains()
    {
        List<ParameterValueInfo> retList = new List<ParameterValueInfo>();

        //if (listBox == null)
        //{
        //    return retList;
        //}

        foreach (RadListViewDataItem dataitem in listBox_NonCustomParamList1.Items)
        {
            RadComboBox ddl = dataitem.FindControl("ddl") as RadComboBox;
            //if (ddl.SelectedValue == ViewState["ID"])
            //{
            ParameterValueInfo newInfo = new ParameterValueInfo();

            newInfo.ID = new Guid(dataitem.GetDataKeyValue("ID").ToString());
            newInfo.Value = ddl.Text;
            retList.Add(newInfo);
            //break;
            //}
        }

        return retList;
    }


    private void StartDownLoad()
    {
        GridItemCollection gicol = dataGridView_subFamilyTable.SelectedItems;

        Guid instanceId = Guid.Empty;
        string fileName = string.Empty;
        if (gicol == null || gicol.Count > 0)
        {
            try
            {
                instanceId = new Guid(gicol[0].Cells[2].Text);
                fileName = gicol[0].Cells[4].Text;
            }
            catch (Exception)
            {
            }

        }

        Guid familyId = Guid.Empty;

        if (HttpContext.Current.Session["familyId"] != null)
        {
            familyId = new Guid(HttpContext.Current.Session["familyId"].ToString());
        }
        List<ParameterValueInfo> driveParameterVals = SABLL.GetDriveParameterVals(familyId, instanceId);
        if (driveParameterVals == null)
        {
            SABLL.ShowErrMsg(this, SABLL.GetLastErrMsg());
            return;
        }

        List<ParameterValueInfo> customParameterVals = this.GetAllCustomParameterVals();
        if (customParameterVals == null) return;

        bool success = ApplyCustomDriveParameters(ref driveParameterVals, customParameterVals);
        if (!success) return;

        List<ParameterInfo> driveParameterInfos = new List<ParameterInfo>();

        for (int i = 0; i < driveParameterVals.Count; i++)
        {
            ParameterInfo newParamInfo = SABLL.GetFamilyParameterInfo(driveParameterVals[i].ID);
            newParamInfo.Value = driveParameterVals[i].Value;
            driveParameterInfos.Add(newParamInfo);
        }

        //
        //show download frm, get the target path and file type.
        FamilyAttrInfo tempAttr = SABLL.GetFamilyAttrInfo(familyId);

        if (fileName == string.Empty)
        {
            fileName = tempAttr.ReferenceName;
        }

        string targetPath = String.Empty;

        //?????????????????????????
        targetPath = Path.Combine(@"C:\", fileName + "." + comboBox_filetype.Text);

        //string radalertscript = "<script language='javascript'>function f(){var win = window.radopen('DownLoadFrm.aspx','Details');win.setSize(600, 300); win.center(); Sys.Application.remove_load(f);}; Sys.Application.add_load(f);</script>";
        //Page.ClientScript.RegisterStartupScript(this.GetType(), "radalert", radalertscript);

        success = SABLL.GeneratePart(this, familyId, instanceId, driveParameterInfos, targetPath);

        if (!success)
        {
            SABLL.ShowErrMsg(this, SABLL.GetLastErrMsg());
            return;
        }
        //else if (success)
        //{
        //    SABLL.ShowInfoMsg(this,"下载成功：" + targetPath);
        //    return;
        //}

    }
    private List<ParameterValueInfo> GetAllCustomParameterVals()
    {
        List<ParameterValueInfo> retList = new List<ParameterValueInfo>();
        string id = null;
        for (int i = 0; i < listBox_CustomParamList1.Items.Count; i++)
        {
            ParameterValueInfo retInfo = new ParameterValueInfo();

            id = listBox_CustomParamList1.DataKeys[i].Value.ToString();
            TextBox txtBox = (TextBox)listBox_CustomParamList1.Items[i].FindControl("Label1");

            if (id == null)
            {
                SABLL.ShowErrMsg(this, "自定义参数数据丢失，请重新打开下载窗口！");
                return null;
            }
            if (txtBox.ForeColor == Color.Red) //incorrect data. return.
            {
                SABLL.ShowErrMsg(this, String.Format("自定义参数 [{0}] 的值 [{1}] 无效，请重新设置！", id, txtBox.Text));
                return null;
            }


            retInfo.ID = new Guid(id);
            retInfo.Value = txtBox.Text.Trim();
            retList.Add(retInfo);
        }

        return retList;
    }

    private bool ApplyCustomDriveParameters(ref List<ParameterValueInfo> driveParameterVals, List<ParameterValueInfo> customParameterVals)
    {
        foreach (ParameterValueInfo customParamVal in customParameterVals)
        {
            foreach (ParameterValueInfo driveParamVal in driveParameterVals)
            {
                if (driveParamVal.ID == customParamVal.ID)
                {
                    driveParamVal.Value = customParamVal.Value;
                    break;
                }
            }
        }
        return true;
    }
    protected void LbtnLink_Click(object sender, EventArgs e)
    {
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("ComponentsIntro.aspx");
    }

    protected void Help_Click(object sender, EventArgs e)
    {
        Response.Redirect("ComponentsIntro.aspx");
    }

}
